package cjq.demo.nio.ch2_4;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * Created by cjq on 2016/4/18.
 */
public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel,AsyncTimeServerHandler> {
    //从attachment获取成员变量AsynchronousServerSocketChannel，然后调用accept
    //再次调用accept方法的原因：
    //当调用AsynchronousServerSocketChannel的accept后，若有新的客户端接入，则回调completed方法，表示新客户端已经接入成功，
    //因为一个AsynchronousServerSocketChannel可以接收成千上万个客户端，所以要继续调用它的accept,接收其他的客户端连接，
    //最终形成一个循环
    //每当接收一个客户端连接成功之后，再异步接收新的客户端连接。
    public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) {
        attachment.asynchronousServerSocketChannel.accept(attachment,this);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        result.read(buffer,buffer,new ReadCompletionHandler(result));
    }

    public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
        exc.printStackTrace();
        attachment.latch.countDown();
    }
}
